import React,{useEffect} from 'react';
import { renderRoutes } from 'react-router-config';
import { connect } from "react-redux";
import { forceCheck } from 'react-lazyload';

import Slider from '../../components/slider';
import RecommendList from '../../components/list';
import Scroll from '../../baseUI/scroll/index';
import { Content } from './style';
import * as actionTypes from './store/actionCreators';
import Loading from '../../baseUI/loading/index';
import { EnterLoading } from './../Singers/style';

function Recommend (props) {
  const { bannerList, recommendList, enterLoading } = props;
  const { getBannerDataDispatch, getRecommendListDataDispatch } = props;
  const { songsCount } = props;

  useEffect (() => {
    if (!bannerList.size){
      getBannerDataDispatch ();
    }
    if (!recommendList.size){
      getRecommendListDataDispatch ();
    }
    //eslint-disable-next-line
  }, []);

  const bannerListJS = bannerList ? bannerList.toJS () : [];
  const recommendListJS = recommendList ? recommendList.toJS () :[];

  /*
    可能你会不解,Content 样式组件是个什么鬼？在这里我要强调一下,better-scroll 的原理并不复杂,就是在容器元素高度固定,当子元素高度超过容器元素高度时,通过 transfrom 动画产生滑动效果,因此它的使用原则就是外部容器必须是固定高度,不然没法滚动。而 Content 就是这个外部容器
  ↓↓ */
  return (
    <Content play={songsCount}>
      <Scroll className="list" onScroll={forceCheck}>{/**←不加这个forceCheck的话,向下滚动时,新进入的img就一直会使用的是占位图片,而不会发请求请求真实图片*/}
        <div>
          <Slider bannerList={bannerListJS}></Slider>
          <RecommendList recommendList={recommendListJS}></RecommendList>
        </div>
      </Scroll>
      {enterLoading? <EnterLoading><Loading></Loading></EnterLoading> : null}
      { renderRoutes(props.route.routes) }
    </Content>
  )
}

// 映射 Redux 全局的 state 到组件的 props 上
const mapStateToProps = (state) => ({
  // 不要在这里将数据 toJS
  // 不然每次 diff 比对 props 的时候都是不一样的引用，还是导致不必要的重渲染，属于滥用 immutable
  bannerList: state.getIn (['recommend', 'bannerList']),//store/reducer.js 中使用了 redux-immutable combineReducers方法, 故这里可以也是需要用.getIn
  recommendList: state.getIn (['recommend', 'recommendList']),
  enterLoading: state.getIn (['recommend', 'enterLoading']),

  songsCount: state.getIn (['player', 'playList']).size // 尽量减少 toJS 操作，直接取 size 属性就代表了 list 的长度
});
// 映射 dispatch 到 props 上
const mapDispatchToProps = (dispatch) => {
  return {
    getBannerDataDispatch () {
      dispatch (actionTypes.getBannerList ());
    },
    getRecommendListDataDispatch () {
      dispatch (actionTypes.getRecommendList ());
    },
  }
};

export default connect (mapStateToProps, mapDispatchToProps)(React.memo (Recommend));
